//
//  BiXingPanDuanTiViewController.swift
//  CKC
//
//  Created by 张振东 on 2016/10/20.
//  Copyright © 2016年 ZZD. All rights reserved.
//

import UIKit
import RealmSwift

class BiXingPanDuanTiViewController: UIViewController {

    let screenWidth = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    var navigationHeight:CGFloat?

    //定义一个iamgeView,存储随机生成的图片
    var topImageView:UIImageView?
    
    //定义一个变量:记录题号的值,默认为1
    var tiHao:Int = 1
    
    //定义一个变量:记录产生的随机数的值
    var randomNumber:UInt32?
    var tiHaoLabel:UILabel?
    var tiGanNeiRongLabel:UILabel?
    var randomNumberLable:UILabel?
    var zuoKuoHaoLabel:UILabel?
    var selectedOptionLabel:UILabel?
    var youKuoHaoLabel:UILabel?

    var randomNumberValue:Int?
    
    //定义两个按钮,记录A、B
    var buttonA:UIButton?
    var buttonB:UIButton?
    
    //定义两个label对象
    var zhengQueLabel:UILabel?
    var cuoWuLabel:UILabel?
    
    //定义两个按钮:保存,下一题
    var saveBtn:UIButton?
    var nextQuestionBtn:UIButton?
    
    //定义一个变量,用于存储从文件夹中读取的图片资源列表
    var imageList:[String]?
    
    var topImageName:String?
    
    //定义一个变量,保存生成的图片的笔形吗
    var topImageViewBiXingCode:Int = 0
    
    override func viewDidLoad() {
        
        
        fengZhuangKongJianShuXing()
        fengZhuangViewDidLoad()
        //弹出一个提示框,显示没有收藏题了
        let alertController = UIAlertController(title: "温馨提示",
                                                message: "亲,您共有20道热身题哦,如果您选择正确,按钮颜色将变为绿色,如果错误,按钮将变为灰色!!", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "好的", style: .default, handler: {
            action in
            print("点击了确定")
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
        // Do any additional setup after loading the view.
    }
    
    
    /*
     作者:张振东
     日期:2017-10-20
     功能:封装lable属性
     */
    func fengZhuangLabelAttributes(_ label:UILabel){
        label.font = UIFont(name: "FontAwesome",size: 15)
        switch label {
        case tiHaoLabel!:
            label.text = "\(tiHao)"
            label.font = UIFont(name: "FontAwesome",size: 20)
            break
        case tiGanNeiRongLabel!:
            label.text = "、以下笔形对应的笔形码为"
            break
        case randomNumberLable!:
            label.font = UIFont(name: "FontAwesome",size: 17)
            if let randomNumber = randomNumber{
                label.text = "\(randomNumber)"
                label.textColor = UIColor.red
            }
            break
        case zuoKuoHaoLabel!:
            label.text = ".("
            break
        case selectedOptionLabel!:
            label.text = ""
            break
        case youKuoHaoLabel!:
            youKuoHaoLabel?.text = ")"
            break
        case zhengQueLabel!:
            zhengQueLabel?.text = "正确"
            break
        case cuoWuLabel!:
            cuoWuLabel?.text = "错误"
            break
        default:
            
            print("封装完毕")
        }
    }

    
    /*
     作者:张振东
     日期:2017-10-20
     功能:封装button属性
     */
    func fengZhuangButtonAttributes(_ button:UIButton){
        
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.backgroundColor = UIColor(red: 231/255,green: 76/255,blue: 60/255,alpha: 1)
        button.layer.cornerRadius = 20
        switch button {
        case buttonA!:
            button.setTitle("A", for: UIControlState())
            break
        case buttonB!:
            button.setTitle("B", for: UIControlState())
            break
        case saveBtn!:
            button.setTitle("收藏", for: UIControlState())
            break
        case nextQuestionBtn!:
            button.setTitle("下一个", for: UIControlState())
            break

        default:
            print("封装button")
        }
    }
    
    /*
     作者:张振东
     时间:2016-10-20
     功能:封装ViewDidLoad
     */
    func fengZhuangViewDidLoad(){
        suiJiShengChengYiGeShu()
        fengZhuangKongJianShuXing()
        let biXingPath = Bundle.main.path(forResource: "bixingimage",ofType: nil, inDirectory: nil)
        print(biXingPath as Any)
        
        //从制定的目录下面读取文件
        do{
            try imageList = FileManager.default.contentsOfDirectory(atPath: biXingPath!)
            if imageList != nil{
                imageList?.remove(at: 0)
            }
        }
        catch let nsError as NSError{
            print(nsError)
        }
        
        
        buttonA?.addTarget(self, action: #selector(clickButtonA), for: .touchUpInside)
        buttonB?.addTarget(self, action: #selector(clickButtonB), for: .touchUpInside)
        saveBtn?.addTarget(self, action: #selector(clickSaveBtn), for: .touchUpInside)
        nextQuestionBtn?.addTarget(self, action: #selector(clickNextQuestion), for: .touchUpInside)
        
        self.view.addSubview(topImageView!)
        self.view.addSubview(tiHaoLabel!)
        self.view.addSubview(tiGanNeiRongLabel!)
        self.view.addSubview(randomNumberLable!)
        self.view.addSubview(zuoKuoHaoLabel!)
        self.view.addSubview(selectedOptionLabel!)
        self.view.addSubview(youKuoHaoLabel!)
        self.view.addSubview(buttonA!)
        self.view.addSubview(buttonB!)
        self.view.addSubview(zhengQueLabel!)
        self.view.addSubview(cuoWuLabel!)
        self.view.addSubview(saveBtn!)
        self.view.addSubview(nextQuestionBtn!)
        shengChengTuPianBingFuZhi()
        super.viewDidLoad()
    
    }

    func fengZhuangKongJianShuXing(){
        self.title = "判断题热身"
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white,NSFontAttributeName:UIFont(name: "STHeitiSC-Medium", size: 20.0)!]
        
        self.view.backgroundColor = UIColor(red: 246,green: 246,blue: 246,alpha: 1)
        let leftBarButton = UIButton(frame:CGRect(x: 0,y: 0,width: 20,height: 20))
        leftBarButton.setBackgroundImage(UIImage(named: "fanhui"), for: UIControlState())
        leftBarButton.addTarget(self, action: #selector(backToPrevious), for: .touchUpInside)
        let leftBarButtonItem = UIBarButtonItem(customView: leftBarButton)
        self.navigationItem.leftBarButtonItems = [leftBarButtonItem]
        
        //设置右边的按钮
        let rightBarButton = UIButton(frame:CGRect(x: screenWidth-20,y: 0,width: 20,height: 20))
        rightBarButton.setBackgroundImage(UIImage(named: "chakanshoucang"), for: UIControlState())
        let rightBarButtonItem = UIBarButtonItem(customView: rightBarButton)
        rightBarButton.addTarget(self, action: #selector(chaKanShouCangPanTuanTiMu), for: .touchUpInside)
        self.navigationItem.rightBarButtonItems = [rightBarButtonItem]
        
        //获取导航栏的高度
        navigationHeight = self.navigationController?.navigationBar.bounds.size.height
        
        //初始化iamgeView
        topImageView = UIImageView(frame:CGRect(x:50,y:navigationHeight!+30,width:screenWidth-100,height:screenWidth-100))
        topImageView!.contentMode = .scaleAspectFit
        
        //初始化题干label对象
        tiHaoLabel = UILabel(frame:CGRect(x: 10,y: navigationHeight!+screenWidth-60,width: 25,height: 30))
        fengZhuangLabelAttributes(tiHaoLabel!)
        
        //初始化题干内容label对象
        tiGanNeiRongLabel = UILabel(frame:CGRect(x: 30,y: navigationHeight!+screenWidth-60,width: 210,height: 30))
        fengZhuangLabelAttributes(tiGanNeiRongLabel!)
        
        //初始化随机生成数label对象
        randomNumberLable = UILabel(frame:CGRect(x: 240,y: navigationHeight!+screenWidth-60,width: 20,height: 30))
        fengZhuangLabelAttributes(randomNumberLable!)
        
        //初始化左括号label对象
        zuoKuoHaoLabel = UILabel(frame:CGRect(x: 255,y: navigationHeight!+screenWidth-60,width: 10,height: 30))
        fengZhuangLabelAttributes(zuoKuoHaoLabel!)
        
        
        //初始选中的选项Label对象
        selectedOptionLabel = UILabel(frame:CGRect(x: 270,y: navigationHeight!+screenWidth-60,width: 15,height: 30))
        fengZhuangLabelAttributes(selectedOptionLabel!)
        
        //初始化右括号label对象
        youKuoHaoLabel = UILabel(frame:CGRect(x: 285,y: navigationHeight!+screenWidth-60,width: 10,height: 30))
        fengZhuangLabelAttributes(youKuoHaoLabel!)
        
        //初始化两个按钮
        buttonA = UIButton(frame:CGRect(x: 40,y: navigationHeight!+screenWidth,width: 40,height: 40))
        fengZhuangButtonAttributes(buttonA!)
        
        buttonB = UIButton(frame:CGRect(x: screenWidth/2+40,y: navigationHeight!+screenWidth,width: 40,height: 40))
        fengZhuangButtonAttributes(buttonB!)
        
        //初始化两个label对象
        zhengQueLabel = UILabel(frame:CGRect(x: 40+40,y: navigationHeight!+screenWidth,width: 40,height: 40))
        fengZhuangLabelAttributes(zhengQueLabel!)
        
        
        cuoWuLabel = UILabel(frame:CGRect(x: screenWidth/2+40+40,y: navigationHeight!+screenWidth,width: 40,height: 40))
        fengZhuangLabelAttributes(cuoWuLabel!)
        
        
        //初始化两个按钮
        buttonA = UIButton(frame:CGRect(x: 40,y: navigationHeight!+screenWidth,width: 40,height: 40))
        fengZhuangButtonAttributes(buttonA!)
        
        buttonB = UIButton(frame:CGRect(x: screenWidth/2+40,y: navigationHeight!+screenWidth,width: 40,height: 40))
        fengZhuangButtonAttributes(buttonB!)
        
        //初始化两个label对象
        zhengQueLabel = UILabel(frame:CGRect(x: 40+40,y: navigationHeight!+screenWidth,width: 40,height: 40))
        fengZhuangLabelAttributes(zhengQueLabel!)
        
        
        cuoWuLabel = UILabel(frame:CGRect(x: screenWidth/2+40+40,y: navigationHeight!+screenWidth,width: 40,height: 40))
        fengZhuangLabelAttributes(cuoWuLabel!)
        
        
        //初始化保存按钮
        saveBtn = UIButton(frame:CGRect(x: 10,y: screenHeight-50,width: (screenWidth-40)/2,height: 40))
        fengZhuangButtonAttributes(saveBtn!)
        
        nextQuestionBtn = UIButton(frame:CGRect(x: screenWidth/2+10,y: screenHeight-50,width: (screenWidth-40)/2,height: 40))
        
        //初始化下一题按钮
        fengZhuangButtonAttributes(nextQuestionBtn!)

    }
    
    /*
     作者:张振东
     时间:2016-10-20
     功能:实现图片的随记生成
     */
    func shengChengTuPianBingFuZhi(){
        if let cancelImageListOptional = imageList{
            print(cancelImageListOptional)
            //获得该[String]数组的长度
            let arrayOfLength = cancelImageListOptional.count
            print(arrayOfLength)
            //随记生成一个0-[String]数组的长度的整数
            let randomNumber:UInt32 = arc4random_uniform(UInt32(arrayOfLength))
            print(randomNumber)
            //通过第三步得到的数字可以获得该数组对应的值(也就是图片的名字)
            topImageName = cancelImageListOptional[Int(randomNumber)]
            topImageView?.image = UIImage(named: topImageName!)
            
            topImageViewBiXingCode = Int(((topImageName! as NSString)).substring(with: NSMakeRange(0, 1)))!
            print(topImageViewBiXingCode)
            
        }
    }

    /*
     作者:张振东
     时间:2016-10-22
     功能:按钮A被点击
     */
    func clickButtonA(){
        //表示选中的为正确答案
        print(randomNumberValue as Any)
        if randomNumberValue != topImageViewBiXingCode{
            buttonA?.backgroundColor = UIColor.gray
            selectedOptionLabel?.text = "A"
        }else{
            buttonA?.backgroundColor = UIColor.green
            selectedOptionLabel?.text = "A"
        }
    }
    
    /*
     作者:张振东
     时间:2016-10-22
     功能:按钮B被点击
     */
    func clickButtonB(){
        //表示选中的为正确答案
        
            print(randomNumberValue as Any)
            if randomNumberValue != topImageViewBiXingCode{
                buttonB?.backgroundColor = UIColor.green
                selectedOptionLabel?.text = "B"
                
            }else{
                buttonB?.backgroundColor = UIColor.gray
                selectedOptionLabel?.text = "B"
        }
        
    }
    
    /*
        作者:张振东
        时间:2016-10-22
        功能:按钮"下一个"被点击
    */
    func clickNextQuestion(){
        //1、题号会自动加一
        tiHao = tiHao + 1
        if tiHao <= 20{
            self.tiHaoLabel?.text = "\(tiHao)"
            
            //2、将上次的对象清空
            self.tiHaoLabel?.text = ""
            self.randomNumberLable?.text = ""
            self.selectedOptionLabel?.text = ""
            self.tiGanNeiRongLabel?.text = ""
            self.zuoKuoHaoLabel?.text = ""
            self.youKuoHaoLabel?.text = ""
            self.zhengQueLabel?.text = ""
            self.cuoWuLabel?.text = ""
            
            //3、题干内容重新加载,不发生变化
            fengZhuangViewDidLoad()

        }else{
            //让下一个按钮失去交互性
            nextQuestionBtn?.isUserInteractionEnabled = false
            //热身结束了
            let alertController = UIAlertController(title: "温馨提示",
                                                    message: "亲,热身结束了!!", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "好的", style: .default, handler: {
                action in
                print("点击了确定")
            })
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }
        
    }
    
    /*
        作者:张振东
        时间:2016-10-22
        功能:按钮"收藏"被点击
    */
    func clickSaveBtn(){
        //将需要保存的属性封装为类对象进行存储
        let biXingPanDuanTi = BiXingPanDuanTi()
        
        biXingPanDuanTi.topImageName = self.topImageName
        print(biXingPanDuanTi.topImageName as Any)
        
        biXingPanDuanTi.tiHao = self.tiHaoLabel?.text
        print(biXingPanDuanTi.tiHao as Any)
        
        biXingPanDuanTi.randomNumber = self.randomNumberLable?.text
        print(biXingPanDuanTi.randomNumber as Any)
        
        biXingPanDuanTi.selectedOptionValue = self.selectedOptionLabel?.text
        print(biXingPanDuanTi.selectedOptionValue as Any)
        
        //使用默认的数据库
        let realm = try! Realm()
        try! realm.write {
            realm.add(biXingPanDuanTi)
        }
        
        //打印出数据库地址
        print(realm.configuration.fileURL as Any)
        
        //弹出一个提示框,显示没有收藏题了
        let alertController = UIAlertController(title: "温馨提示",
                                                message: "亲,收藏成功了!!", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "好的", style: .default, handler: {
            action in
            print("点击了确定")
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    /*
     作者:张振东
     时间:2016-10-21
     功能:查看收藏的判断题
    */
    func chaKanShouCangPanTuanTiMu(){
        let chaKanBiXingShouCangPanDuanTiViewController = ChaKanBiXingShouCangPanDuanTiViewController()
        self.navigationController?.pushViewController(chaKanBiXingShouCangPanDuanTiViewController, animated: true)
    }

    /*
     作者:张振东
     日期:2017-10-20
     功能:随机生成一个0-10之间的数
     */
    func suiJiShengChengYiGeShu(){
        randomNumber = arc4random_uniform(UInt32(10))
        randomNumberValue = Int(randomNumber!)
    }
    
    func backToPrevious(){
        self.navigationController?.popViewController(animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
